#!/usr/bin/python
import time, os, sys
from django.conf import settings
import django.template
import django.template.loader
from django.db import connection

from django.db import backend
DatabaseWarning = backend.Database.Warning

from migration.models import Version
try:
  rootdir = settings._DIRNAME
except:
  _DIRNAME = os.path.dirname(os.path.abspath(globals()["__file__"]))
  sys.path.append( os.path.join(_DIRNAME, '..') )
  rootdir = _DIRNAME
  
from django.core.management.base import NoArgsCommand
from optparse import make_option

warnings = []

class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list 
    
    help = "Evolves the Database Schema"

    requires_model_validation = False

    def handle_noargs(self, **options):
        while migrate():
            pass
        
        if len(warnings) > 0:
            print "%s Database WARNINGS OCCURED." % len(warnings)


def migrate():
    version = Version.objects.all()[0]
    current = version.version
    next = "%04d" % (current + 1)

    path_python = os.path.join(rootdir, 'upgrades', '%s.py' % next)
    path_sql = os.path.join(rootdir, 'upgrades', '%s.sql' % next)
    
    if os.access(path_sql, os.F_OK):
        do_migrate('sql', path_sql, next)
    elif os.access(path_python, os.F_OK):
        do_migrate('python', path_python, next)
    else:        
        print "%s is latest revision" % current
        return False

    
    print "Finished upgrading to revision %s." % next

    version.upgrade()
    
    return True    

def do_migrate(method, path, next):
    print "Upgrading to revision %s." % next
    
    if method == 'sql':
        upgrades = open(path, "r").readlines()        
        for upgrade in upgrades:
            if upgrade.lstrip() == '':
                continue
            
            print upgrade

            cursor = connection.cursor()
            try:
                cursor.execute(upgrade)
            except DatabaseWarning, e:
                warnings.append(e)
                print "Database WARNING: %s" % e
            
    elif method == 'python':
        print '--- PYTHON FILE ---'
        print open(path, "r").read()
        print '--- END PYTHON FILE ---'
        execfile(path)
    
